<?
if (!defined('SMF'))
	die('Hacking attempt...');
	
global $smcFunc, $txt, $scripturl;
global $dbtables, $sector_max, $universe_size;
global $fed_max_hull;
global $ore_limit, $organics_limit, $goods_limit, $energy_limit;
global $default_prod_ore, $default_prod_organics, $default_prod_goods, $default_prod_energy;
global $default_prod_fighters, $default_prod_torp;
global $sched_ticks;
global $sched_turns, $sched_ports, $sched_planets, $sched_igb;
global $sched_ranking, $sched_news, $sched_degrade, $sched_apocalypse;
global $xenobe_max;

// Read in old settings
// Placeholder for once the config file is in the database

$phase = (isset($_POST['phase'])) ? $_POST['phase'] : '1';

switch ($phase)
{
	// Phase 1, Default form to get new game settings
	case '1':
		echo '
			<form action="', $scripturl, '?action=admin;area=blacknovagame;sa=game_reset" method="post">
				<h3>Reset Universe - Base/Planet Settings</h3>
				<ul>
					<li><label>Percent Special</label><input type="text" name="special" size="10" maxlength="10" value="1" /></li>
				    <li><label>Percent Ore</label><input type="text" name="ore" size="10" maxlength="10" value="15" /></li>
				    <li><label>Percent Organics</label><input type="text" name="organics" size="10" maxlength="10" value="10" /></li>
				    <li><label>Percent Goods</label><input type="text" name="goods" size="10" maxlength="10" value="15" /></li>
				    <li><label>Percent Energy</label><input type="text" name="energy" size="10" maxlength="10" value="10" /></li>
					<li>Percent Empty will be equal to 100 minus the total of above.</li>

					<li><label>Initial Commodities to Sell [% of max]</label><input type="text" name="initscommod" size="10" maxlength="10" value="100.00" /></li>
					<li><label>Initial Commodities to Buy [% of max]</label><input type="text" name="initbcommod" size="10" maxlength="10" value="100.00" /></li>
				</ul>';
			
		$fedsecs = intval($sector_max / 200);
		$loops = intval($sector_max / 500);

		echo '
				<h3>Reset Universe  - Sector/Link Setttings</h3>
				<ul>
					<li><label>Number of sectors total (<b>overrides config.php</b>)</label><input type="text" name="sectors" size="10" maxlength="10" value="', $sector_max, '" /></li>
					<li><label>Number of Federation sectors</label><input type="text" name="fedsecs" size="10" maxlength="10" value="', $fedsecs, '" /></li>
					<li><label>Number of loops</label><input type="text" name="sector_loops" size="10" maxlength="10" value="', $loops, '" /></li>
					<li><label>Percent of sectors with unowned planets</label><input type="text" name="planets" size="10" maxlength="10" value="10" /></li>

				    <li><input type="hidden" name="phase" value="2" /></li>

					<li><input type="submit" value="Next"></li>
				</ul>
			</form>';
		break;
	
	// Phase 2, Confirmation form before beginning actual universe creation
	case '2':
		// Get POST variables from phase 1
		$special = $_POST['special'];
		$ore = $_POST['ore'];
		$organics = $_POST['organics'];
		$goods = $_POST['goods'];
		$energy = $_POST['energy'];
		$initscommod = $_POST['initscommod'];
		$initbcommod = $_POST['initbcommod'];
		$sectors = $_POST['sectors'];
		$fedsecs = $_POST['fedsecs'];
		$sector_loops = $_POST['sector_loops'];
		$planets = $_POST['planets'];
		
		// Sector check
		$sector_max = round($sectors);
		if ($fedsecs > $sector_max)
		{
			echo 'The number of Federation sectors must be smaller than the size of the universe!';
			break;
		}
		
		$spp = round($sector_max * $special / 100);
		$oep = round($sector_max * $ore / 100);
		$ogp = round($sector_max * $organics / 100);
		$gop = round($sector_max * $goods / 100);
		$enp = round($sector_max * $energy / 100);
		$empty = $sector_max - $spp - $oep - $ogp - $gop - $enp;
		$nump = round ($sector_max * $planets / 100);
		
		echo '
			<form action="', $scripturl, '?action=admin;area=blacknovagame;sa=game_reset" method=post>
				<input type="hidden" name="phase" value="3" />
				<input type="hidden" name="spp" value="', $spp, '" />
				<input type="hidden" name="oep" value="', $oep, '" />
				<input type="hidden" name="ogp" value="', $ogp, '" />
				<input type="hidden" name="gop" value="', $gop, '" />
				<input type="hidden" name="enp" value="', $enp, '" />
				<input type="hidden" name="initscommod" value="', $initscommod, '" />
				<input type="hidden" name="initbcommod" value="', $initbcommod, '" />
				<input type="hidden" name="nump" value="', $nump, '" />
				<input type="hidden" name="fedsecs" value="', $fedsecs, '" />
				<input type="hidden" name="sector_loops" value="', $sector_loops, '" />
				
				<h3>Reset Universe - Confirmation</h3>
				
				<ul>
					<li><label>Sector Max:</label>', $sectors, '</li>
				    <li><label>Special ports:</label>', $spp, '</li>
				    <li><label>Ore ports:</label>', $oep, '</li>
				    <li><label>Organics ports:</label>', $ogp, '</li>
				    <li><label>Goods ports:</label>', $gop, '</li>
				    <li><label> Energy ports:</label>', $enp, '</li>
				    <li><label>Initial commodities to sell:</label>', $initscommod, '%</li>
				    <li><label>Initial commodities to buy:</label>', $initbcommod, '%</li>
				    <li><label>Empty sectors:</label>', $empty, '</li>
				    <li><label>Federation sectors:</label>', $fedsecs, '</li>
				    <li><label>Loops:</label>', $sector_loops, '</li>
				    <li><label>Unowned planets:</label>', $nump, '</li>
					<li><input type="submit" value="Confirm"></li>
				</ul>

				<h3>WARNING: ALL DATABASE TABLES WILL BE CLEARED AND THE GAME WILL BE RESET WHEN YOU CLICK CONFIRM!</h3>
			</form>';
		break;
	
	// Phase 3, Admin has confirm universe creation, ensure tables exist, delete all rows from the BNT tables.
	case '3':
		// Get POST variables from phase 2
		$spp = $_POST['spp'];
		$oep = $_POST['oep'];
		$ogp = $_POST['ogp'];
		$gop = $_POST['gop'];
		$enp = $_POST['enp'];
		$initscommod = $_POST['initscommod'];
		$initbcommod = $_POST['initbcommod'];
		$nump = $_POST['nump'];
		$fedsecs = $_POST['fedsecs'];
		$sector_loops = $_POST['sector_loops'];
		
		// Ensure BNT Tables exist
		include("schema.php");
		
		// Setup database tables array in prepraration for truncating.
		$db_array =	array(
						'db_bounty' => $dbtables['bounty'],
						'db_ibank_accounts' => $dbtables['ibank_accounts'],
						'db_IGB_transfers' => $dbtables['IGB_transfers'],
						'db_ip_bans' => $dbtables['ip_bans'],
						'db_links' => $dbtables['links'],
						'db_logs' => $dbtables['logs'],
						'db_messages' => $dbtables['messages'],
						'db_movement_log' => $dbtables['movement_log'],
						'db_news' => $dbtables['news'],
						'db_planets' => $dbtables['planets'],
						'db_scheduler' => $dbtables['scheduler'],
						'db_sector_defence' => $dbtables['sector_defence'],
						'db_ships' => $dbtables['ships'],
						'db_teams' => $dbtables['teams'],
						'db_traderoutes' => $dbtables['traderoutes'],
						'db_universe' => $dbtables['universe'],
						'db_xenobes' => $dbtables['xenobes'],
						'db_zones' => $dbtables['zones'],
					);
		
		// Loop through the db_array and delete all rows from the BNT tables
		foreach ($db_array as $table_alias)
		{
			$smcFunc['db_query']('','
					TRUNCATE {raw:table}',
				array(
					'table' => $table_alias,
				)
			);
		}
		
		echo '
			<h3>Database Reset Complete!</h3>
			<form action="', $scripturl, '?action=admin;area=blacknovagame;sa=game_reset" method=post>
				<input type="hidden" name="phase" value="4" />
				<input type="hidden" name="spp" value="', $spp, '" />
				<input type="hidden" name="oep" value="', $oep, '" />
				<input type="hidden" name="ogp" value="', $ogp, '" />
				<input type="hidden" name="gop" value="', $gop, '" />
				<input type="hidden" name="enp" value="', $enp, '" />
				<input type="hidden" name="initscommod" value="', $initscommod, '" />
				<input type="hidden" name="initbcommod" value="', $initbcommod, '" />
				<input type="hidden" name="nump" value="', $nump, '" />
				<input type="hidden" name="fedsecs" value="', $fedsecs, '" />
				<input type="hidden" name="sector_loops" value="', $sector_loops, '" />				
				<p><input type="submit" value="Next"></p>
			</form>';
		break;
	
	// Phase 4, beging to populate the database with ports
	case '4':
		// Get POST variables from phase 3
		$spp = $_POST['spp'];
		$oep = $_POST['oep'];
		$ogp = $_POST['ogp'];
		$gop = $_POST['gop'];
		$enp = $_POST['enp'];
		$initscommod = $_POST['initscommod'];
		$initbcommod = $_POST['initbcommod'];
		$nump = $_POST['nump'];
		$fedsecs = $_POST['fedsecs'];
		$sector_loops = $_POST['sector_loops'];
		
		// This block was run many times in the .55 Classic, I have removed
		// the duplication so that it is only run once.
		$initsore = $ore_limit * $initscommod / 100.0;
		$initsorganics = $organics_limit * $initscommod / 100.0;
		$initsgoods = $goods_limit * $initscommod / 100.0;
		$initsenergy = $energy_limit * $initscommod / 100.0;
		$initbore = $ore_limit * $initbcommod / 100.0;
		$initborganics = $organics_limit * $initbcommod / 100.0;
		$initbgoods = $goods_limit * $initbcommod / 100.0;
		$initbenergy = $energy_limit * $initbcommod / 100.0;
		
		echo '
			<h3>Creating Sol, Sector 0</h3>';
		$smcFunc['db_insert']('insert',
			$dbtables['universe'],
			array(
				'sector_id' => 'int',
				'sector_name' => 'string',
				'zone_id' => 'int',
				'port_type' => 'string',
				'port_organics' => 'int',
				'port_ore' => 'int',
				'port_goods' => 'int',
				'port_energy' => 'int',
				'beacon' => 'string',
				'angle1' => 'int',
				'angle2' => 'int',
				'distance' => 'int',
			),
			array(
				0,
				'Sol',
				1,
				'special',
				0,
				0,
				0,
				0,
				'Sol: Hub of the Universe',
				0,
				0,
				0,
			),
			''
		);

		echo '
			<h3>Converting Sol Sector Id to 0</h3>';
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_universe}
			SET sector_id = 0
			WHERE sector_id = 1',
			array(
				'db_universe' => $dbtables['universe'],
			)
		);
		
		echo '
			<h3>Creating Alpha Centauri in Sector 1</h3>';
		$smcFunc['db_insert']('insert',
			$dbtables['universe'],
			array(
				'sector_id' => 'int',
				'sector_name' => 'string',
				'zone_id' => 'int',
				'port_type' => 'string',
				'port_organics' => 'int',
				'port_ore' => 'int',
				'port_goods' => 'int',
				'port_energy' => 'int',
				'beacon' => 'string',
				'angle1' => 'int',
				'angle2' => 'int',
				'distance' => 'int',
			),
			array(
				1,
				'Alpha Centauri',
				1,
				'energy',
				0,
				0,
				0,
				0,
				'Alpha Centauri: Gateway to the Galaxy',
				0,
				0,
				1,
			),
			''
		);
		
		echo '
			<h3>Building Remaining Sectors</h3>
			<ul>';
			
		// Flush the buffer before we begin the big loops
		flush();
		
		// Setup the remaining sectors to process
		$remaining = $sector_max - 1;
		
		// Setup the load balancing loop, providing a 50/50 load balance
		// between MySQL queries and PHP processing.
		// Balancing algorithm written by The Mighty Dude
		$loopsize = 500;
        $loops = round($sector_max / $loopsize) + 1;
        if ($loops <= 0)
			$loops = 1;	
		$finish = $loopsize;
        if ($finish > ($sector_max))
			$finish = $sector_max;
		
		//Always start from sector 2, as sectors 0 and 1 are already setup
		$start = 2;

        for ($i = 1; $i <= $loops; $i++)
        {
			$insert_values = array();
			for ($j = $start; $j < $finish; $j++)
			{
				$distance = intval(rand(1,$universe_size));
				$angle1 = rand(0,180);
				$angle2 = rand(0,90);
				$insert_values[] = array(1, $angle1, $angle2, $distance);
			}

			if ($start < $sector_max && $finish <= $sector_max)
			{
				$smcFunc['db_insert']('insert',
					$dbtables['universe'],
					array(
						'zone_id' => 'int',
						'angle1' => 'int',
						'angle2' => 'int',
						'distance' => 'int',
					),
					$insert_values,
					''
				);
			}

			echo '
				<li>Inserting loop ', $i, ' of ', $loops, ' Sector Block [', $start, ' - ', $finish - 1, '] into the Universe.</li>';

			$start = $finish;
			$finish += $loopsize;
			if ($finish > $sector_max)
				$finish = $sector_max;
				
			// Flush the buffer to keep display up to date	
			flush();
        }
		
		echo '
			</ul>
			<h3>Setting up Zone (Unchartered space)</h3>';	

		$smcFunc['db_insert']('replace',
			$dbtables['zones'],
			array(
				'zone_id' => 'int',
				'zone_name' => 'string',
				'owner' => 'int',
				'corp_zone' => 'string',
				'allow_beacon' => 'string',
				'allow_attack' => 'string',
				'allow_planetattack' => 'string',
				'allow_warpedit' => 'string',
				'allow_planet' => 'string',
				'allow_trade' => 'string',
				'allow_defenses' => 'string',
				'max_hull' => 'int',
			),
			array(
				1,
				'Unchartered space',
				0,
				'N',
				'Y',
				'Y',
				'Y',
				'Y',
				'Y',
				'Y',
				'Y',
				0,
			),
			''
		);

		echo '
			<h3>Setting up Zone (Federation space)</h3>';	

		$smcFunc['db_insert']('replace',
			$dbtables['zones'],
			array(
				'zone_id' => 'int',
				'zone_name' => 'string',
				'owner' => 'int',
				'corp_zone' => 'string',
				'allow_beacon' => 'string',
				'allow_attack' => 'string',
				'allow_planetattack' => 'string',
				'allow_warpedit' => 'string',
				'allow_planet' => 'string',
				'allow_trade' => 'string',
				'allow_defenses' => 'string',
				'max_hull' => 'int',
			),
			array(
				2,
				'Federation space',
				0,
				'N',
				'N',
				'N',
				'N',
				'N',
				'N',
				'Y',
				'N',
				$fed_max_hull,
			),
			''
		);
		
		echo '
			<h3>Setting up Zone (Free-Trade space)</h3>';	

		$smcFunc['db_insert']('replace',
			$dbtables['zones'],
			array(
				'zone_id' => 'int',
				'zone_name' => 'string',
				'owner' => 'int',
				'corp_zone' => 'string',
				'allow_beacon' => 'string',
				'allow_attack' => 'string',
				'allow_planetattack' => 'string',
				'allow_warpedit' => 'string',
				'allow_planet' => 'string',
				'allow_trade' => 'string',
				'allow_defenses' => 'string',
				'max_hull' => 'int',
			),
			array(
				3,
				'Free-Trade space',
				0,
				'N',
				'N',
				'Y',
				'N',
				'N',
				'N',
				'Y',
				'N',
				0,
			),
			''
		);

		echo '
			<h3>Setting up Zone (War Zone)</h3>';	

		$smcFunc['db_insert']('replace',
			$dbtables['zones'],
			array(
				'zone_id' => 'int',
				'zone_name' => 'string',
				'owner' => 'int',
				'corp_zone' => 'string',
				'allow_beacon' => 'string',
				'allow_attack' => 'string',
				'allow_planetattack' => 'string',
				'allow_warpedit' => 'string',
				'allow_planet' => 'string',
				'allow_trade' => 'string',
				'allow_defenses' => 'string',
				'max_hull' => 'int',
			),
			array(
				4,
				'War Zone',
				0,
				'N',
				'Y',
				'Y',
				'Y',
				'Y',
				'Y',
				'N',
				'Y',
				0,
			),
			''
		);
		
		echo '
			<h3>Setting up ', $fedsecs, ' Federation Sectors</h3>';	
		
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_universe}
			SET zone_id = 2
			WHERE sector_id < {int:fedsecs}',
			array(
				'db_universe' => $dbtables['universe'],
				'fedsecs' => $fedsecs,
			)
		);
		
		// Flush the buffer to keep display up to date	
		flush();
		
		// Setup the load balancing loop, providing a 50/50 load balance
		// between MySQL queries and PHP processing.
		// Balancing algorithm written by The Mighty Dude
		$loopsize = 500;
        $loops = round($spp / $loopsize);
        if ($loops <= 0)
			$loops = 1;
        $finish = $loopsize;
        if ($finish > $spp)
			$finish = $spp;

		// First special port is already created, so start from 1.
        $start = 1;
		
		echo '
			<h3>Setting up Special Ports</h3>
			<ul>';
		
		// Get a result of all empty sectors in random order limited by the number of 
		// special ports we are going to create.
		$result = $smcFunc['db_query']('', '
			SELECT sector_id
			FROM {raw:db_universe}
			WHERE port_type = "none"
			ORDER BY rand() DESC
			LIMIT {int:spp}',
			array(
				'db_universe' => $dbtables['universe'],
				'spp' => $spp
			)
		);
		
		
		// Begin to build the special port update query.
		$update_query = '
			UPDATE ' . $dbtables['universe'] . '
			SET zone_id = 3,
				port_type = "special"
			WHERE ';

        for ($i = 1; $i <= $loops; $i++)
        {
            $update_query = '
				UPDATE ' . $dbtables['universe'] . '
				SET zone_id = 3,
					port_type = "special"
				WHERE ';
				
            for ($j = $start; $j < $finish; $j++)
            {
                $row = $smcFunc['db_fetch_assoc']($result);
                $update_query .= '(port_type = "none" AND sector_id = ' . $row['sector_id'] . ')';
				
                if ($j < ($finish - 1))
					$update_query .= ' OR ';
            }
			
			// Execute the special port update query.
			$update = $smcFunc['db_query']('', 
				$update_query,
				''
			);
			
			echo '
				<li>Loop ', $i, ' of ', $loops, ' (Setting up Special Ports) Block [', $start + 1, ' - ', $finish, '] into the Universe.</li>';

            $start = $finish;
            $finish += $loopsize;
            if ($finish > $spp)
				$finish = $spp;
				
			// Flush the buffer to keep display up to date	
			flush();
        }
		
		$smcFunc['db_free_result']($result);
		
		// Begin setup of ore ports in the universe.
		echo '
			</ul>
			<h3>Setting up Ore Ports</h3>
			<ul>';
		
		// Setup the load balancing loop, providing a 50/50 load balance
		// between MySQL queries and PHP processing.
		// Balancing algorithm written by The Mighty Dude
        $loopsize = 500;
        $loops = round($oep / $loopsize);
        if ($loops <= 0)
			$loops = 1;
        $finish = $loopsize;
        if ($finish > $oep)
			$finish = $oep;
        $start = 0;
		
		// Get a result of all empty sectors in random order limited by the number of 
		// ore ports we are going to create.
		$result = $smcFunc['db_query']('', '
			SELECT sector_id
			FROM {raw:db_universe}
			WHERE port_type = "none"
			ORDER BY rand() DESC
			LIMIT {int:oep}',
			array(
				'db_universe' => $dbtables['universe'],
				'oep' => $oep
			)
		);
		
		// Begin to build the ore port update query.
		$update_query = '
			UPDATE ' . $dbtables['universe'] . '
			SET port_type = "ore",
				port_ore = ' . $initsore . ',
				port_organics = ' . $initborganics . ',
				port_goods = ' . $initbgoods . ',
				port_energy = ' . $initbenergy . '
			WHERE ';

        for ($i = 1; $i <= $loops; $i++)
        {
			$update_query = '
				UPDATE ' . $dbtables['universe'] . '
				SET port_type = "ore",
					port_ore = ' . $initsore . ',
					port_organics = ' . $initborganics . ',
					port_goods = ' . $initbgoods . ',
					port_energy = ' . $initbenergy . '
				WHERE ';
				
            for ($j = $start; $j < $finish; $j++)
            {
                $row = $smcFunc['db_fetch_assoc']($result);
                $update_query .= '(port_type = "none" AND sector_id = ' . $row['sector_id'] . ')';
				
                if ($j < ($finish - 1))
					$update_query .= ' OR ';
            }
			
			// Execute to build the ore port update query.
			$update = $smcFunc['db_query']('', 
				$update_query,
				''
			);
			
			echo '
				<li>Loop ', $i, ' of ', $loops, ' (Setting up Ore Ports) Block [', $start + 1, ' - ', $finish, '].</li>';

            $start = $finish;
            $finish += $loopsize;
            if ($finish > $oep)
				$finish = $oep;
				
			// Flush the buffer to keep display up to date	
			flush();
        }
		
		$smcFunc['db_free_result']($result);
		
		
		// Begin setup of Organics ports in the universe.
		echo '
			</ul>
			<h3>Setting up Organics Ports</h3>
			<ul>';
		
		// Setup the load balancing loop, providing a 50/50 load balance
		// between MySQL queries and PHP processing.
		// Balancing algorithm written by The Mighty Dude
        $loopsize = 500;
        $loops = round($ogp / $loopsize);
        if ($loops <= 0)
			$loops = 1;
        $finish = $loopsize;
        if ($finish > $ogp)
			$finish = $ogp;
        $start = 0;
		
		// Get a result of all empty sectors in random order limited by the number of 
		// organics ports we are going to create.
		$result = $smcFunc['db_query']('', '
			SELECT sector_id
			FROM {raw:db_universe}
			WHERE port_type = "none"
			ORDER BY rand() DESC
			LIMIT {int:ogp}',
			array(
				'db_universe' => $dbtables['universe'],
				'ogp' => $ogp
			)
		);
		
		// Begin to build the organics port update query.
		$update_query = '
			UPDATE ' . $dbtables['universe'] . '
			SET port_type = "organics",
				port_ore = ' . $initbore . ',
				port_organics = ' . $initsorganics . ',
				port_goods = ' . $initbgoods . ',
				port_energy = ' . $initbenergy . '
			WHERE ';

        for ($i = 1; $i <= $loops; $i++)
        {
			$update_query = '
				UPDATE ' . $dbtables['universe'] . '
				SET port_type = "organics",
					port_ore = ' . $initbore . ',
					port_organics = ' . $initsorganics . ',
					port_goods = ' . $initbgoods . ',
					port_energy = ' . $initbenergy . '
				WHERE ';
				
            for ($j = $start; $j < $finish; $j++)
            {
                $row = $smcFunc['db_fetch_assoc']($result);
                $update_query .= '(port_type = "none" AND sector_id = ' . $row['sector_id'] . ')';
				
                if ($j < ($finish - 1))
					$update_query .= ' OR ';
            }
			
			// Execute to build the ore port update query.
			$update = $smcFunc['db_query']('', 
				$update_query,
				''
			);
			
			echo '
				<li>Loop ', $i, ' of ', $loops, ' (Setting up Organics Ports) Block [', $start + 1, ' - ', $finish, '].</li>';

            $start = $finish;
            $finish += $loopsize;
            if ($finish > $ogp)
				$finish = $ogp;
				
			// Flush the buffer to keep display up to date	
			flush();
        }
		
		$smcFunc['db_free_result']($result);
		
		
		// Begin setup of goods ports in the universe.
		echo '
			</ul>
			<h3>Setting up Goods Ports</h3>
			<ul>';
		
		// Setup the load balancing loop, providing a 50/50 load balance
		// between MySQL queries and PHP processing.
		// Balancing algorithm written by The Mighty Dude.
        $loopsize = 500;
        $loops = round($gop / $loopsize);
        if ($loops <= 0)
			$loops = 1;
        $finish = $loopsize;
        if ($finish > $gop)
			$finish = $gop;
        $start = 0;
		
		// Get a result of all empty sectors in random order limited by the number of 
		// goods ports we are going to create.
		$result = $smcFunc['db_query']('', '
			SELECT sector_id
			FROM {raw:db_universe}
			WHERE port_type = "none"
			ORDER BY rand() DESC
			LIMIT {int:gop}',
			array(
				'db_universe' => $dbtables['universe'],
				'gop' => $gop
			)
		);
		
		// Begin to build the goods port update query.
		$update_query = '
			UPDATE ' . $dbtables['universe'] . '
			SET port_type = "goods",
				port_ore = ' . $initbore . ',
				port_organics = ' . $initborganics . ',
				port_goods = ' . $initsgoods . ',
				port_energy = ' . $initbenergy . '
			WHERE ';

        for ($i = 1; $i <= $loops; $i++)
        {
			$update_query = '
				UPDATE ' . $dbtables['universe'] . '
				SET port_type = "goods",
					port_ore = ' . $initbore . ',
					port_organics = ' . $initborganics . ',
					port_goods = ' . $initsgoods . ',
					port_energy = ' . $initbenergy . '
				WHERE ';
				
            for ($j = $start; $j < $finish; $j++)
            {
                $row = $smcFunc['db_fetch_assoc']($result);
                $update_query .= '(port_type = "none" AND sector_id = ' . $row['sector_id'] . ')';
				
                if ($j < ($finish - 1))
					$update_query .= ' OR ';
            }
			
			// Execute to build the goods port update query.
			$update = $smcFunc['db_query']('', 
				$update_query,
				''
			);
			
			echo '
				<li>Loop ', $i, ' of ', $loops, ' (Setting up Goods Ports) Block [', $start + 1, ' - ', $finish, '].</li>';

            $start = $finish;
            $finish += $loopsize;
            if ($finish > $gop)
				$finish = $gop;
				
			// Flush the buffer to keep display up to date	
			flush();
        }
		
		$smcFunc['db_free_result']($result);
		
		
		// Begin setup of energy ports in the universe.
		echo '
			</ul>
			<h3>Setting up Energy Ports</h3>
			<ul>';
		
		// Setup the load balancing loop, providing a 50/50 load balance
		// between MySQL queries and PHP processing.
		// Balancing algorithm written by The Mighty Dude.
        $loopsize = 500;
        $loops = round($enp / $loopsize);
        if ($loops <= 0)
			$loops = 1;
        $finish = $loopsize;
        if ($finish > $enp)
			$finish = $enp;
			
        // There is a hard coded energy port created already, start from 1.
        $start = 1;
		
		// Get a result of all empty sectors in random order limited by the number of 
		// energy ports we are going to create.
		$result = $smcFunc['db_query']('', '
			SELECT sector_id
			FROM {raw:db_universe}
			WHERE port_type = "none"
			ORDER BY rand() DESC
			LIMIT {int:enp}',
			array(
				'db_universe' => $dbtables['universe'],
				'enp' => $enp
			)
		);
		
		// Begin to build the energy port update query.
		$update_query = '
			UPDATE ' . $dbtables['universe'] . '
			SET port_type = "energy",
				port_ore = ' . $initbore . ',
				port_organics = ' . $initborganics . ',
				port_goods = ' . $initsgoods . ',
				port_energy = ' . $initbenergy . '
			WHERE ';

        for ($i = 1; $i <= $loops; $i++)
        {
			$update_query = '
				UPDATE ' . $dbtables['universe'] . '
				SET port_type = "energy",
					port_ore = ' . $initbore . ',
					port_organics = ' . $initborganics . ',
					port_goods = ' . $initsgoods . ',
					port_energy = ' . $initbenergy . '
				WHERE ';
				
            for ($j = $start; $j < $finish; $j++)
            {
                $row = $smcFunc['db_fetch_assoc']($result);
                $update_query .= '(port_type = "none" AND sector_id = ' . $row['sector_id'] . ')';
				
                if ($j < ($finish - 1))
					$update_query .= ' OR ';
            }
			
			// Execute to build the energy port update query.
			$update = $smcFunc['db_query']('', 
				$update_query,
				''
			);
			
			echo '
				<li>Loop ', $i, ' of ', $loops, ' (Setting up Energy Ports) Block [', $start + 1, ' - ', $finish, '].</li>';

            $start = $finish;
            $finish += $loopsize;
            if ($finish > $enp)
				$finish = $enp;
				
			// Flush the buffer to keep display up to date	
			flush();
        }
		
		$smcFunc['db_free_result']($result);
		
		echo '
			</ul>
			<h3>Port Creation Complete!</h3>';
		
		echo '
			<form action="', $scripturl, '?action=admin;area=blacknovagame;sa=game_reset" method=post>
				<input type="hidden" name="phase" value="5" />
				<input type="hidden" name="spp" value="', $spp, '" />
				<input type="hidden" name="oep" value="', $oep, '" />
				<input type="hidden" name="ogp" value="', $ogp, '" />
				<input type="hidden" name="gop" value="', $gop, '" />
				<input type="hidden" name="enp" value="', $enp, '" />
				<input type="hidden" name="initscommod" value="', $initscommod, '" />
				<input type="hidden" name="initbcommod" value="', $initbcommod, '" />
				<input type="hidden" name="nump" value="', $nump, '" />
				<input type="hidden" name="fedsecs" value="', $fedsecs, '" />
				<input type="hidden" name="sector_loops" value="', $sector_loops, '" />				
				<p><input type="submit" value="Next"></p>
			</form>';
		break;
	
	// Phase 5, Create planets and sector links.
	case '5':
		// Get POST variables from phase 4
		$spp = $_POST['spp'];
		$oep = $_POST['oep'];
		$ogp = $_POST['ogp'];
		$gop = $_POST['gop'];
		$enp = $_POST['enp'];
		$initscommod = $_POST['initscommod'];
		$initbcommod = $_POST['initbcommod'];
		$nump = $_POST['nump'];
		$fedsecs = $_POST['fedsecs'];
		$sector_loops = $_POST['sector_loops'];
		
        $p_add = 0;
		$p_skip = 0;
		$i = 0;
		
		echo '
			<h3>Selecting ', $nump, ' sectors to place unowned planets in.</h3>';
		flush();
		
        do
        {
            $num = rand(2, ($sector_max - 1));
			$result = $smcFunc['db_query']('', '
				SELECT {raw:db_universe}.sector_id
				FROM {raw:db_universe}, {raw:db_zones}
				WHERE {raw:db_universe}.sector_id = {int:num}
				AND {raw:db_zones}.zone_id = {raw:db_universe}.zone_id
				AND {raw:db_zones}.allow_planet = "N"',
				array(
					'db_universe' => $dbtables['universe'],
					'db_zones' => $dbtables['zones'],
					'num' => $num,
				)
			);

            if ($smcFunc['db_num_rows']($result) == 0)
            {
				$smcFunc['db_insert']('insert',
					$dbtables['planets'],
					array(
						'colonists' => 'int',
						'owner' => 'int',
						'corp' => 'int',
						'prod_ore' => 'int',
						'prod_organics' => 'int',
						'prod_goods' => 'int',
						'prod_energy' => 'int',
						'prod_fighters' => 'int',
						'prod_torp' => 'int',
						'sector_id' => 'int',
					),
					array(
						2,
						0,
						0,
						$default_prod_ore,
						$default_prod_organics,
						$default_prod_goods,
						$default_prod_energy,
						$default_prod_fighters,
						$default_prod_torp,
						$num,
					),
					''
				);
				$p_add++;
            }
        }
        while ($p_add < $nump);
		
		$smcFunc['db_free_result']($result);
		
		
		// Add links to the link table using the formula sector size * 2 amount of links.
		// This has the effect of creating a one way link between all sectors in the game.
		echo '
			<h3>Creating sequential sector links.</h3>
			<ul>';
		flush();
		
		// Setup the load balancing loop, providing a 50/50 load balance
		// between MySQL queries and PHP processing.
		// Balancing algorithm written by TheMightyDude.
        $loopsize = 500;
        $loops = round($sector_max / $loopsize) + 1;
        if ($loops <= 0)
			$loops = 1;
        $finish = $loopsize;
        if ($finish > $sector_max)
			$finish = $sector_max;
		$start = 0;

		for ($i = 1; $i <= $loops; $i++)
        {
			for ($j = $start; $j < $finish; $j++)
			{
                $k = $j + 1;
                $insert_values[] = array($j,$k);
				$insert_values[] = array($k,$j);
			}

			if ($start < $sector_max && $finish <= $sector_max)
			{
				$smcFunc['db_insert']('insert',
					$dbtables['links'],
					array(
						'link_start' => 'int',
						'link_dest' => 'int',
					),
					$insert_values,
					''
				);
			}

			echo '
				<li>Creating loop ', $i, ' of ', $loops, ' (from sector ', $start, ' to ', $finish - 1, ') loop ', $i, '</li>';

			$start = $finish;
			$finish += $loopsize;
			if ($finish > $sector_max)
				$finish = $sector_max;
			
			// Empty the $insert_values
			$insert_values = '';
			
			// Flush the buffer to keep display up to date	
			flush();
        }

		
		// Create random one way sector links
		echo '
			</ul>
			<h3>Creating random one way sector links.</h3>
			<ul>';
		flush();
		
		// Setup the load balancing loop, providing a 50/50 load balance
		// between MySQL queries and PHP processing.
		// Balancing algorithm written by TheMightyDude.
        $loopsize = 500;
        $loops = round($sector_max / $loopsize) + 1;
        if ($loops <= 0)
			$loops = 1;
        $finish = $loopsize;
        if ($finish > $sector_max)
			$finish = $sector_max;
		$start = 0;

		for ($i = 1; $i <= $loops; $i++)
        {
			for ($j = $start; $j < $finish; $j++)
			{
                $link1 = intval(rand(1,$sector_max - 1));
                $link2 = intval(rand(1,$sector_max - 1));
                $insert_values[] = array($link1,$link2);
			}

			if ($start < $sector_max && $finish <= $sector_max)
			{
				$smcFunc['db_insert']('insert',
					$dbtables['links'],
					array(
						'link_start' => 'int',
						'link_dest' => 'int',
					),
					$insert_values,
					''
				);
			}

			echo '
				<li>Creating loop ', $i, ' of ', $loops, ' Random One Way Links (from sector ', $start, ' to ', $finish - 1, ') loop ', $i, '</li>';

			$start = $finish;
			$finish += $loopsize;
			if ($finish > $sector_max)
				$finish = $sector_max;
				
			// Empty the $insert_values
			$insert_values = '';
			
			// Flush the buffer to keep display up to date	
			flush();
        }
		
		
		// Create random two way sector links
		echo '
			</ul>
			<h3>Creating random two way sector links.</h3>
			<ul>';
		flush();
		
		// Setup the load balancing loop, providing a 50/50 load balance
		// between MySQL queries and PHP processing.
		// Balancing algorithm written by TheMightyDude.
        $loopsize = 500;
        $loops = round($sector_max / $loopsize) + 1;
        if ($loops <= 0)
			$loops = 1;
        $finish = $loopsize;
        if ($finish > $sector_max)
			$finish = $sector_max;
		$start = 0;

		for ($i = 1; $i <= $loops; $i++)
        {
			for ($j = $start; $j < $finish; $j++)
			{
                $link1 = intval(rand(1,$sector_max - 1));
                $link2 = intval(rand(1,$sector_max - 1));
                $insert_values[] = array($link1,$link2);
				$insert_values[] = array($link2,$link1);
			}

			if ($start < $sector_max && $finish <= $sector_max)
			{
				$smcFunc['db_insert']('insert',
					$dbtables['links'],
					array(
						'link_start' => 'int',
						'link_dest' => 'int',
					),
					$insert_values,
					''
				);
			}

			echo '
				<li>Creating loop ', $i, ' of ', $loops, ' Random Two Way Links (from sector ', $start, ' to ', $finish - 1, ') loop ', $i, '</li>';

			$start = $finish;
			$finish += $loopsize;
			if ($finish > $sector_max)
				$finish = $sector_max;
				
			// Empty the $insert_values
			$insert_values = '';	
			
			// Flush the buffer to keep display up to date	
			flush();
        }
		
		echo '
			</ul>
			<h3>Planet and Link creation complete.</h3>';
		
		echo '
			<form action="', $scripturl, '?action=admin;area=blacknovagame;sa=game_reset" method=post>
				<input type="hidden" name="phase" value="6" />
				<input type="hidden" name="spp" value="', $spp, '" />
				<input type="hidden" name="oep" value="', $oep, '" />
				<input type="hidden" name="ogp" value="', $ogp, '" />
				<input type="hidden" name="gop" value="', $gop, '" />
				<input type="hidden" name="enp" value="', $enp, '" />
				<input type="hidden" name="initscommod" value="', $initscommod, '" />
				<input type="hidden" name="initbcommod" value="', $initbcommod, '" />
				<input type="hidden" name="nump" value="', $nump, '" />
				<input type="hidden" name="fedsecs" value="', $fedsecs, '" />
				<input type="hidden" name="loops" value="', $loops, '" />				
				<p><input type="submit" value="Next"></p>
			</form>';
		
		break;
	
	// Phase 6, Configure game scehduler.
	case 6:
		// Get POST variables from phase 5
		$spp = $_POST['spp'];
		$oep = $_POST['oep'];
		$ogp = $_POST['ogp'];
		$gop = $_POST['gop'];
		$enp = $_POST['enp'];
		$initscommod = $_POST['initscommod'];
		$initbcommod = $_POST['initbcommod'];
		$nump = $_POST['nump'];
		$fedsecs = $_POST['fedsecs'];
		$loops = $_POST['loops'];
	
		echo '
			<h3>Configuring game scheduler.</h3>
			<p>Update ticks will occur every ', $sched_ticks, ' minutes.<p>';
		
		// Insert the scheduled turns row.
		echo'
			<p>Turns will occur every ', $sched_turns, ' minutes</p>';
		$smcFunc['db_insert']('insert',
			$dbtables['scheduler'],
			array(
				'repeate' => 'string',
				'ticks_left' => 'int',
				'ticks_full' => 'int',
				'spawn' => 'int',
				'sched_file' => 'string',
				'next_run' => 'string',
			),
			array(
				'Y',
				0,
				$sched_turns,
				0,
				'sched_turns.php',
				time() + $sched_turns * 60
			),
			''
		);
		
		// Insert the scheduled defenses row.
		echo '
			<p>Defenses will be checked every ', $sched_turns, ' minutes</p>';
		$smcFunc['db_insert']('insert',
			$dbtables['scheduler'],
			array(
				'repeate' => 'string',
				'ticks_left' => 'int',
				'ticks_full' => 'int',
				'spawn' => 'int',
				'sched_file' => 'string',
				'next_run' => 'string',
			),
			array(
				'Y',
				0,
				$sched_turns,
				0,
				'sched_defenses.php',
				time() + $sched_turns * 60
			),
			''
		);
		
		if ($xenobe_max > 0)
		{
			// Insert the scheduled xenobe row.
			echo '
				<p>Xenobes will play every ', $sched_turns, ' minutes</p>';
			$smcFunc['db_insert']('insert',
				$dbtables['scheduler'],
				array(
					'repeate' => 'string',
					'ticks_left' => 'int',
					'ticks_full' => 'int',
					'spawn' => 'int',
					'sched_file' => 'string',
					'next_run' => 'string',
				),
				array(
					'Y',
					0,
					$sched_turns,
					0,
					'sched_xenobe.php',
					time() + $sched_turns * 60
				),
				''
			);
		}

		// Insert the scheduled IGB interest row.
		echo '
			<p>Interests on IGB accounts will be accumulated every ', $sched_igb, ' minutes</p>';
		$smcFunc['db_insert']('insert',
			$dbtables['scheduler'],
			array(
				'repeate' => 'string',
				'ticks_left' => 'int',
				'ticks_full' => 'int',
				'spawn' => 'int',
				'sched_file' => 'string',
				'next_run' => 'string',
			),
			array(
				'Y',
				0,
				$sched_turns,
				0,
				'sched_igb.php',
				time() + $sched_igb * 60
			),
			''
		);

		// Insert the scheduled news row.
		echo '
			<p>News will be generated every ', $sched_news, ' minutes</p>';
		$smcFunc['db_insert']('insert',
			$dbtables['scheduler'],
			array(
				'repeate' => 'string',
				'ticks_left' => 'int',
				'ticks_full' => 'int',
				'spawn' => 'int',
				'sched_file' => 'string',
				'next_run' => 'string',
			),
			array(
				'Y',
				0,
				$sched_news,
				0,
				'sched_news.php',
				time() + $sched_news * 60
			),
			''
		);

		// Insert the scheduled planets row.
		echo '
			<p>Planets will generate production every ', $sched_planets, ' minutes</p>';
		$smcFunc['db_insert']('insert',
			$dbtables['scheduler'],
			array(
				'repeate' => 'string',
				'ticks_left' => 'int',
				'ticks_full' => 'int',
				'spawn' => 'int',
				'sched_file' => 'string',
				'next_run' => 'string',
			),
			array(
				'Y',
				0,
				$sched_planets,
				0,
				'sched_planets.php',
				time() + $sched_planets * 60
			),
			''
		);
		
		// Insert the scheduled ports row.
		echo '
			<p>Ports will regenerate every ', $sched_ports, ' minutes</p>';
		$smcFunc['db_insert']('insert',
			$dbtables['scheduler'],
			array(
				'repeate' => 'string',
				'ticks_left' => 'int',
				'ticks_full' => 'int',
				'spawn' => 'int',
				'sched_file' => 'string',
				'next_run' => 'string',
			),
			array(
				'Y',
				0,
				$sched_ports,
				0,
				'sched_ports.php',
				time() + $sched_ports * 60
			),
			''
		);
		
		// Insert the scheduled tow row.
		echo '
			<p>Ships will be towed from fed sectors every ', $sched_turns, ' minutes</p>';
		$smcFunc['db_insert']('insert',
			$dbtables['scheduler'],
			array(
				'repeate' => 'string',
				'ticks_left' => 'int',
				'ticks_full' => 'int',
				'spawn' => 'int',
				'sched_file' => 'string',
				'next_run' => 'string',
			),
			array(
				'Y',
				0,
				$sched_turns,
				0,
				'sched_tow.php',
				time() + $sched_turns * 60
			),
			''
		);

		// Insert the scheduled rankings row.
		echo '
			<p>Rankings will be generated every ', $sched_ranking, ' minutes</p>';
		$smcFunc['db_insert']('insert',
			$dbtables['scheduler'],
			array(
				'repeate' => 'string',
				'ticks_left' => 'int',
				'ticks_full' => 'int',
				'spawn' => 'int',
				'sched_file' => 'string',
				'next_run' => 'string',
			),
			array(
				'Y',
				0,
				$sched_ranking,
				0,
				'sched_ranking.php',
				time() + $sched_ranking * 60
			),
			''
		);
		
		// Insert the scheduled sector defences row.
		echo '
			<p>Sector Defences will degrade every ', $sched_degrade, ' minutes</p>';
		$smcFunc['db_insert']('insert',
			$dbtables['scheduler'],
			array(
				'repeate' => 'string',
				'ticks_left' => 'int',
				'ticks_full' => 'int',
				'spawn' => 'int',
				'sched_file' => 'string',
				'next_run' => 'string',
			),
			array(
				'Y',
				0,
				$sched_degrade,
				0,
				'sched_degrade.php',
				time() + $sched_degrade * 60
			),
			''
		);

		// Insert the scheduled planetary apocalypse row.
		echo '
			<p>The planetary apocalypse will occurevery ', $sched_apocalypse, ' minutes</p>';
		$smcFunc['db_insert']('insert',
			$dbtables['scheduler'],
			array(
				'repeate' => 'string',
				'ticks_left' => 'int',
				'ticks_full' => 'int',
				'spawn' => 'int',
				'sched_file' => 'string',
				'next_run' => 'string',
			),
			array(
				'Y',
				0,
				$sched_apocalypse,
				0,
				'sched_apocalypse.php',
				time() + $sched_apocalypse * 60
			),
			''
		);
		
		echo '
			<h3>Scheduler setup complete!</h3>
			<h3>Game setup complete!</h3>
			<p>Click <a href="', $scripturl, '?action=blacknova;sa=login">here</a> to enter the game.</p>';
      break;
}
?>